package net.lzzy.practicesapi1.services;

import net.lzzy.practicesapi1.entities.User;
import net.lzzy.practicesapi1.repositories.UserProjection;
import net.lzzy.practicesapi1.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

/**
 * 1.@Autowired 字段注入，最简单，但无法保证依赖完整性
 * 2.setter注入，时机灵活，可在对象创建后注入；使用于要注入可能用得到可能用不到的对象
 * 3.构造器注入，时机最早，保证对象有值（repository为不可变对象，所以用final修饰）
 * @author 梁园钲
 */
@Service
public class UserServiceImpl implements UserService{
    private final UserRepository repository;
    @Autowired
    public UserServiceImpl(UserRepository repository) {
        this.repository = repository;
    }




    @Override
    public User check(String userName, String password) {
        return repository.findUserByUsernameAndPassword(userName,password);
    }

    @Override
    public boolean isUserNameOccupied(String username) {
        return repository.countByUsername(username)>0;
    }

    @Override
    public User register(User user) {
        return repository.save(user);
    }

    @Override
    public String getSalt(String userName) {
        UserProjection projection = repository.findUserByUsername(userName);
        if(projection == null){
            return "";
        }
        return projection.getSalt();
    }

    @Override
    public List<User> get() {
        return repository.findAllByOrderByUpdateTimeDesc();
    }

    @Override
    public List<User> get(int page, int size) {
        return repository.findAllByOrderByUpdateTimeDesc(PageRequest.of(page,size));
    }

    @Override
    public Integer count() {
        return repository.countAllBy();
    }

    @Override
    public List<User> search(String keyword) {
        return repository.findByQuery(keyword);
    }

    @Override
    public List<User> getApplyTeacher(boolean apply) {
        return repository.findUsersByApplyTeacherOrderByUpdateTimeDesc(apply);
    }

    /**
     * getById是迟加载
     * findByid是早加载
     * @param id
     * @return
     */
    @Override
    public User approveTeacher(UUID id) {
        User user=repository.findById(id).orElse(null);
        if(user != null){
            user.setType(User.TYPE_TEACHER);
            user.setApplyTeacher(false);
            return repository.save(user);
        }
        return null;
    }


    @Override
    public User declineTeacher(UUID id) {
        return null;
    }

    @Override
    public User banUser(UUID id) {
        User user = repository.findById(id).orElse(null);
        if (user != null && user.getType() != User.TYPE_ADMIN) {
            user.setType(User.TYPE_BANNED);
            return repository.save(user);
        }
        return null;
    }

    @Override
    public User getUser(UUID id) {
        return null;
    }
}
